package com.kexilo.core.common.utils;

import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类
 * 
 * @author Kexilo
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {

    /** 空字符串 */
    private static final String NULLSTR = "";

    /** 下划线 */
    private static final char SEPARATOR = '_';

    /**
     * 获取参数不为空值
     * 
     * @param value defaultValue 要判断的value
     * @return value 返回值
     */
    public static <T> T nvl(T value, T defaultValue) {
        return value != null ? value : defaultValue;
    }

    /**
     * * 判断一个Collection是否为空， 包含List，Set，Queue
     * 
     * @param coll 要判断的Collection
     * @return true：为空 false：非空
     */
    public static boolean isEmpty(Collection<?> coll) {
        return isNull(coll) || coll.isEmpty();
    }

    /**
     * * 判断一个Collection是否非空，包含List，Set，Queue
     * 
     * @param coll 要判断的Collection
     * @return true：非空 false：空
     */
    public static boolean isNotEmpty(Collection<?> coll) {
        return !isEmpty(coll);
    }

    /**
     * * 判断一个对象数组是否为空
     * 
     * @param objects 要判断的对象数组
     * @return true：为空 false：非空
     */
    public static boolean isEmpty(Object[] objects) {
        return isNull(objects) || (objects.length == 0);
    }

    /**
     * * 判断一个对象数组是否非空
     * 
     * @param objects 要判断的对象数组
     * @return true：非空 false：空
     */
    public static boolean isNotEmpty(Object[] objects) {
        return !isEmpty(objects);
    }

    /**
     * * 判断一个对象是否为空
     * 
     * @param object Object
     * @return true：为空 false：非空
     */
    public static boolean isNull(Object object) {
        return object == null;
    }

    /**
     * * 判断一个对象是否非空
     * 
     * @param object Object
     * @return true：非空 false：空
     */
    public static boolean isNotNull(Object object) {
        return !isNull(object);
    }

    /**
     * * 判断一个字符串是否为空串
     * 
     * @param str String
     * @return true：为空 false：非空
     */
    public static boolean isEmpty(String str) {
        return isNull(str) || NULLSTR.equals(str.trim());
    }

    /**
     * * 判断一个字符串是否为非空串
     * 
     * @param str String
     * @return true：非空串 false：空串
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    /**
     * * 判断一个字符串是否有文本内容（即不为null且去除空白字符后长度大于0）
     * 
     * @param str String
     * @return true：有文本内容 false：无文本内容
     */
    public static boolean hasText(String str) {
        return str != null && !str.trim().isEmpty();
    }

    /**
     * 格式化文本, {} 表示占位符<br>
     * 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
     * 如果想输出 {} 使用 \\转义 { 即可，如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
     * 例：<br>
     * 通常使用：format("this is {} for {}", "a", "b") -> this is a for b<br>
     * 转义{}： format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
     * 转义\： format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
     * 
     * @param template 文本模板，被替换的部分用 {} 表示
     * @param params 参数值
     * @return 格式化后的文本
     */
    public static String format(String template, Object... params) {
        if (isEmpty(params) || isEmpty(template)) {
            return template;
        }
        return org.apache.commons.lang3.StringUtils.replaceEach(template, buildPlaceholders(params.length), toStringArray(params));
    }

    /**
     * 构建占位符数组
     */
    private static String[] buildPlaceholders(int count) {
        String[] placeholders = new String[count];
        for (int i = 0; i < count; i++) {
            placeholders[i] = "{}";
        }
        return placeholders;
    }

    /**
     * 对象数组转字符串数组
     */
    private static String[] toStringArray(Object[] objects) {
        String[] strings = new String[objects.length];
        for (int i = 0; i < objects.length; i++) {
            strings[i] = nvl(objects[i], "").toString();
        }
        return strings;
    }

    /**
     * 驼峰转下划线命名
     */
    public static String toUnderScoreCase(String str) {
        if (str == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        // 前置字符是否大写
        boolean preCharIsUpperCase = true;
        // 当前字符是否大写
        boolean curreCharIsUpperCase = true;
        // 下一字符是否大写
        boolean nexteCharIsUpperCase = true;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (i > 0) {
                preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
            } else {
                preCharIsUpperCase = false;
            }

            curreCharIsUpperCase = Character.isUpperCase(c);

            if (i < (str.length() - 1)) {
                nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
            }

            if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {
                sb.append(SEPARATOR);
            } else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) {
                sb.append(SEPARATOR);
            }
            sb.append(Character.toLowerCase(c));
        }

        return sb.toString();
    }

    /**
     * 下划线转驼峰命名
     */
    public static String toCamelCase(String str) {
        if (str == null) {
            return null;
        }

        str = str.toLowerCase();

        StringBuilder sb = new StringBuilder(str.length());
        boolean upperCase = false;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);

            if (c == SEPARATOR) {
                upperCase = true;
            } else if (upperCase) {
                sb.append(Character.toUpperCase(c));
                upperCase = false;
            } else {
                sb.append(c);
            }
        }

        return sb.toString();
    }

    /**
     * 首字母转小写
     */
    public static String uncapitalize(String str) {
        if (str == null || str.length() == 0) {
            return str;
        }
        return str.substring(0, 1).toLowerCase() + str.substring(1);
    }

    /**
     * 首字母转大写
     */
    public static String capitalize(String str) {
        if (str == null || str.length() == 0) {
            return str;
        }
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }

    /**
     * 截取字符串
     * 
     * @param str 字符串
     * @param start 开始
     * @return 结果
     */
    public static String substring(final String str, int start) {
        if (str == null) {
            return NULLSTR;
        }

        if (start < 0) {
            start = str.length() + start;
        }

        if (start < 0) {
            start = 0;
        }
        if (start > str.length()) {
            return NULLSTR;
        }

        return str.substring(start);
    }

    /**
     * 截取字符串
     * 
     * @param str 字符串
     * @param start 开始
     * @param end 结束
     * @return 结果
     */
    public static String substring(final String str, int start, int end) {
        if (str == null) {
            return NULLSTR;
        }

        if (end < 0) {
            end = str.length() + end;
        }
        if (start < 0) {
            start = str.length() + start;
        }

        if (end > str.length()) {
            end = str.length();
        }

        if (start > end) {
            return NULLSTR;
        }

        if (start < 0) {
            start = 0;
        }
        if (end < 0) {
            end = 0;
        }

        return str.substring(start, end);
    }

    /**
     * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串
     * 
     * @param str 指定字符串
     * @param strs 需要检查的字符串数组
     * @return 是否匹配
     */
    public static boolean matches(String str, String... strs) {
        if (isEmpty(str) || isEmpty(strs)) {
            return false;
        }
        for (String pattern : strs) {
            if (isMatch(pattern, str)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断url是否与规则配置:
     * ? 表示单个字符;
     * * 表示一层路径内的任意字符串，不可跨层级;
     * ** 表示任意层路径;
     * 
     * @param pattern 匹配模式
     * @param url 需要匹配的url
     * @return
     */
    public static boolean isMatch(String pattern, String url) {
        AntPathMatcher matcher = new AntPathMatcher();
        return matcher.match(pattern, url);
    }

    // 简化版的AntPathMatcher实现
    private static class AntPathMatcher {
        private static final Pattern GLOB_PATTERN = Pattern.compile("\\?|\\*|\\{((?:\\{[^/]+?\\}|[^/{}]|\\\\[{}])+?)\\}");
        private static final String DEFAULT_PATH_SEPARATOR = "/";

        public boolean match(String pattern, String path) {
            return doMatch(pattern, path, true);
        }

        protected boolean doMatch(String pattern, String path, boolean fullMatch) {
            if (path.startsWith(DEFAULT_PATH_SEPARATOR) != pattern.startsWith(DEFAULT_PATH_SEPARATOR)) {
                return false;
            }

            String[] pattDirs = tokenizePattern(pattern);
            String[] pathDirs = tokenizePath(path);

            int pattIdxStart = 0;
            int pattIdxEnd = pattDirs.length - 1;
            int pathIdxStart = 0;
            int pathIdxEnd = pathDirs.length - 1;

            // Match all elements up to the first **
            while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {
                String pattDir = pattDirs[pattIdxStart];
                if ("**".equals(pattDir)) {
                    break;
                }
                if (!matchStrings(pattDir, pathDirs[pathIdxStart])) {
                    return false;
                }
                pattIdxStart++;
                pathIdxStart++;
            }

            if (pathIdxStart > pathIdxEnd) {
                // Path is exhausted, only match if rest of pattern is * or **'s
                if (pattIdxStart > pattIdxEnd) {
                    return (pattern.endsWith(DEFAULT_PATH_SEPARATOR) == path.endsWith(DEFAULT_PATH_SEPARATOR));
                }
                if (!fullMatch) {
                    return true;
                }
                if (pattIdxStart == pattIdxEnd && pattDirs[pattIdxStart].equals("*") && path.endsWith(DEFAULT_PATH_SEPARATOR)) {
                    return true;
                }
                for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
                    if (!pattDirs[i].equals("**")) {
                        return false;
                    }
                }
                return true;
            }
            else if (pattIdxStart > pattIdxEnd) {
                // String not exhausted, but pattern is. Failure.
                return false;
            }
            else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) {
                // Path start definitely matches due to "**" part in pattern.
                return true;
            }

            // up to last '**'
            while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {
                String pattDir = pattDirs[pattIdxEnd];
                if (pattDir.equals("**")) {
                    break;
                }
                if (!matchStrings(pattDir, pathDirs[pathIdxEnd])) {
                    return false;
                }
                pattIdxEnd--;
                pathIdxEnd--;
            }
            if (pathIdxStart > pathIdxEnd) {
                // String is exhausted
                for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
                    if (!pattDirs[i].equals("**")) {
                        return false;
                    }
                }
                return true;
            }

            while (pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd) {
                int patIdxTmp = -1;
                for (int i = pattIdxStart + 1; i <= pattIdxEnd; i++) {
                    if (pattDirs[i].equals("**")) {
                        patIdxTmp = i;
                        break;
                    }
                }
                if (patIdxTmp == pattIdxStart + 1) {
                    // '**/**' situation, so skip one
                    pattIdxStart++;
                    continue;
                }
                // Find the pattern between padIdxStart & padIdxTmp in str between
                // strIdxStart & strIdxEnd
                int patLength = (patIdxTmp - pattIdxStart - 1);
                int strLength = (pathIdxEnd - pathIdxStart + 1);
                int foundIdx = -1;

                strLoop:
                for (int i = 0; i <= strLength - patLength; i++) {
                    for (int j = 0; j < patLength; j++) {
                        String subPat = pattDirs[pattIdxStart + j + 1];
                        String subStr = pathDirs[pathIdxStart + i + j];
                        if (!matchStrings(subPat, subStr)) {
                            continue strLoop;
                        }
                    }
                    foundIdx = pathIdxStart + i;
                    break;
                }

                if (foundIdx == -1) {
                    return false;
                }

                pattIdxStart = patIdxTmp;
                pathIdxStart = foundIdx + patLength;
            }

            for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
                if (!pattDirs[i].equals("**")) {
                    return false;
                }
            }

            return true;
        }

        protected String[] tokenizePattern(String pattern) {
            return tokenizePath(pattern);
        }

        protected String[] tokenizePath(String path) {
            return org.apache.commons.lang3.StringUtils.split(path, DEFAULT_PATH_SEPARATOR);
        }

        private boolean matchStrings(String pattern, String str) {
            char[] patArr = pattern.toCharArray();
            char[] strArr = str.toCharArray();
            int patIdxStart = 0;
            int patIdxEnd = patArr.length - 1;
            int strIdxStart = 0;
            int strIdxEnd = strArr.length - 1;
            char ch;

            boolean containsStar = false;
            for (char c : patArr) {
                if (c == '*') {
                    containsStar = true;
                    break;
                }
            }

            if (!containsStar) {
                // No '*'s, so we make a shortcut
                if (patIdxEnd != strIdxEnd) {
                    return false; // Pattern and string do not have the same size
                }
                for (int i = 0; i <= patIdxEnd; i++) {
                    ch = patArr[i];
                    if (ch != '?' && ch != strArr[i]) {
                        return false; // Character mismatch
                    }
                }
                return true; // String matches against pattern
            }

            if (patIdxEnd == 0) {
                return true; // Pattern contains only '*', which matches everything
            }

            // Process characters before first star
            while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {
                ch = patArr[patIdxStart];
                if (ch == '*') {
                    break;
                }
                if (ch != '?' && ch != strArr[strIdxStart]) {
                    return false; // Character mismatch
                }
                patIdxStart++;
                strIdxStart++;
            }

            // All characters in the string before the star have been matched
            if (strIdxStart > strIdxEnd) {
                // All characters in the string are matched. Check if only '*'s are left
                // in the pattern. If so, then we have a match. Otherwise we have no match.
                for (int i = patIdxStart; i <= patIdxEnd; i++) {
                    if (patArr[i] != '*') {
                        return false;
                    }
                }
                return true;
            }

            // Process characters after last star
            while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) {
                ch = patArr[patIdxEnd];
                if (ch == '*') {
                    break;
                }
                if (ch != '?' && ch != strArr[strIdxEnd]) {
                    return false; // Character mismatch
                }
                patIdxEnd--;
                strIdxEnd--;
            }

            // All characters in the string after the star have been matched
            if (strIdxStart > strIdxEnd) {
                // All characters in the string are matched. Check if only '*'s are left
                // in the pattern. If so, then we have a match. Otherwise we have no match.
                for (int i = patIdxStart; i <= patIdxEnd; i++) {
                    if (patArr[i] != '*') {
                        return false;
                    }
                }
                return true;
            }

            // Process the characters between the star and the last star
            while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {
                int patIdxTmp = -1;
                for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {
                    if (patArr[i] == '*') {
                        patIdxTmp = i;
                        break;
                    }
                }
                if (patIdxTmp == patIdxStart + 1) {
                    // Two stars next to each other, skip the first one.
                    patIdxStart++;
                    continue;
                }

                // Find the pattern between padIdxStart & padIdxTmp in str between
                // strIdxStart & strIdxEnd
                int patLength = (patIdxTmp - patIdxStart - 1);
                int strLength = (strIdxEnd - strIdxStart + 1);
                int foundIdx = -1;
                strLoop:
                for (int i = 0; i <= strLength - patLength; i++) {
                    for (int j = 0; j < patLength; j++) {
                        ch = patArr[patIdxStart + j + 1];
                        if (ch != '?' && ch != strArr[strIdxStart + i + j]) {
                            continue strLoop;
                        }
                    }

                    foundIdx = strIdxStart + i;
                    break;
                }

                if (foundIdx == -1) {
                    return false;
                }

                patIdxStart = patIdxTmp;
                strIdxStart = foundIdx + patLength;
            }

            // All characters in the string are matched. Check if only '*'s are left
            // in the pattern. If so, then we have a match. Otherwise we have no match.
            for (int i = patIdxStart; i <= patIdxEnd; i++) {
                if (patArr[i] != '*') {
                    return false;
                }
            }

            return true;
        }
    }

    /**
     * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串（忽略大小写）
     * 
     * @param str 指定字符串
     * @param strs 需要检查的字符串数组
     * @return 是否匹配
     */
    public static boolean inStringIgnoreCase(String str, String... strs) {
        if (str != null && strs != null) {
            for (String s : strs) {
                if (str.equalsIgnoreCase(trim(s))) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串（忽略大小写）
     * 
     * @param str 指定字符串
     * @param strOne 字符串1
     * @param strTwo 字符串2
     * @return 是否匹配
     */
    public static boolean inStringIgnoreCase(String str, String strOne, String strTwo) {
        return inStringIgnoreCase(str, new String[]{strOne, strTwo});
    }

    /**
     * 判断URL是否是http(s)链接
     * 
     * @param link URL链接
     * @return 是否是http(s)链接
     */
    public static boolean ishttp(String link) {
        if (isEmpty(link)) {
            return false;
        }
        String lowerLink = link.toLowerCase();
        return lowerLink.startsWith("http://") || lowerLink.startsWith("https://");
    }
}
